package algorithm.leetcode.I401to600;


import java.util.Arrays;

/**
 * 思路: 排序之后从哪一个位置开始不一样是左边界,哪一个位置开始又一样是右边界
 */

public class Q581 {

    public int findUnsortedSubarray(int[] nums) {
        int[] clone = nums.clone();
        Arrays.sort(nums);

        int left = -1, right = nums.length;
        for (int i = 0; i < nums.length; i++) {
            if (clone[i] != nums[i] && left == -1) left = i;
            if (clone[nums.length-1-i] != nums[nums.length-1-i] && right == nums.length) right = nums.length-1-i;
        }
        if (left == -1 && right == nums.length) return 0;
        else return right - left + 1;
    }

}
